#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
#include <memory>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Usage: " << argv[0] << " IP Port" << endl;
        exit(-1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int socketfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd < 0)
    {
        exit(-1);
    }

    sockaddr_in server;
    socklen_t len = sizeof(server);
    memset(&server, 0, len);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while (true)
    {
        errno = 0;
        cout << "Enter# ";
        string line;
        getline(cin, line);

        int n = sendto(socketfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, len);
        if (n > 0)
        {
            sockaddr_in tmp;
            socklen_t lentmp = sizeof(tmp);
            char inbuffer[1024] = {0};
            int m = recvfrom(socketfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&tmp, &lentmp);
            if (m > 0)
            {
                inbuffer[m] = '0';
                cout << inbuffer << endl;
            }
            else
            {
                if (errno == EINTR)
                {
                    exit(-1);
                }
                else if (errno == ECONNRESET)
                {
                    exit(-1);
                }
                else
                {
                    break;
                }
            }
        }
        else
        {
            if (errno == EINTR)
            {
                exit(-1);
            }
            else if (errno == ECONNRESET)
            {
                exit(-1);
            }
            {
                break;
            }
        }
    }

    return 0;
}
